#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JilinBaishanPolicy(BaseTaxPolicySpider):
    name = 'jilin_baishan_policy'
    
    province = '吉林省'
    city = '白山市'
    park = ''
    url = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOAD_TIMEOUT": 200,
            },
        }
        settings.setdict(new_settings or {}, priority="spider")
    
    def start_requests(self):
        for source, county, url in [
            ['白山市人民政府', '', 'http://xxgk.cbs.gov.cn/szf/fdzdgknr_1/lzyj/zfwj/'],
            ['浑江区人民政府', '浑江区', 'http://xxgk-hj.cbs.gov.cn/qzf/fdzdgknr/lzyj/'],
            ['江源区人民政府', '江源区', 'http://jy.cbs.gov.cn/zwgk/zfwj/index.html'],
            ['江源区人民政府', '江源区', 'http://xxgk-jy.cbs.gov.cn/szf_1361/fdzdgknr/lzyj/'],
            ['抚松县人民政府', '抚松县', 'http://www.fusong.gov.cn/zwgk/zcwj/'],
            ['抚松县人民政府', '抚松县', 'http://xxgk-fs.cbs.gov.cn/szf_1361/fdzdgknr/lzyj/'],
            ['靖宇县人民政府', '靖宇县', 'http://jyx.cbs.gov.cn/zwgk/zfwj/'],
            ['长白朝鲜族自治县人民政府', '长白朝鲜族自治县', 'http://www.changbai.gov.cn/zwgk/zfwj/'],
            ['临江市人民政府', '临江市', 'http://www.linjiang.gov.cn/sy/zfwj/'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        print(response.url)
        prev_item = response.meta.get('item')
        if '系统繁忙,请稍后点击' in response.text:
            yield scrapy.Request(response.url, callback=self.parse_list, dont_filter=True, meta={'item': prev_item, 'is_next': False})
        elem_list = response.xpath(
            "//table//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//div//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//div//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9] | "
            "//table//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jsp' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下页' in response.text or '下一页' in response.text:
                totalpage = response.xpath(""".""").re_first(r"var countPage\s*=\s*(\d+)") or response.xpath(""".""").re_first(r"Pager\(\{size\:\s*(\d+)")
                print('totalpage', totalpage)
                if totalpage:
                    for page in range(1, int(totalpage) + 1):
                        url = response.url.replace('index.html', '') + f'index_{page}.html'
                        yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
                else:
                    print(response.url)
            else:
                print(response.url)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("""string(//meta[@name='firstpublishedtime']/@content)""").get() or response.xpath(".//*[contains(text(), '发布日期：')]/following-sibling::td/text()").re_first(r"\d{4}年\d{2}月\d{2}")
        item['content'] = response.xpath(""".""").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].replace("年", "-").replace("月", "-")
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jilin_baishan_policy".split())
